package com.dev.op.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dev.op.VO.ResultVO;
import com.dev.op.entity.User;
import com.dev.op.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users")
@PreAuthorize("hasAnyRole('admin')")
public class UserController {

    @Resource
    private UserService userService;

    // 获取所有用户
    @GetMapping
    public ResultVO<Page<User>> getUserList(@RequestParam("page") String page,
                                            @RequestParam("size") String size) {
       return ResultVO.success(userService.getUsersWithoutPassword(Integer.parseInt(page), Integer.parseInt(size)));
    }

    // 根据 ID 获取用户
    @GetMapping("/{id}")
    public ResultVO<User> getUserById(@PathVariable String id) {
        User user = userService.getById(id);
        user.setPassword(null);
        return ResultVO.success(user);
    }

    // 创建用户
    @PostMapping
    public ResultVO<Boolean> createUser(@RequestBody User user) {
        boolean res = userService.save(user);
        user.setPassword(null);
        return ResultVO.success(res);
    }

    // 更新用户
    @PutMapping
    public ResultVO<Boolean> updateUser( @RequestBody User user) {
        boolean res = userService.updateById(user);
        return ResultVO.success(res);
    }

    // 删除用户
    @DeleteMapping("/{id}")
    public ResultVO<Boolean> deleteUser(@PathVariable String id) {
        Boolean res = userService.removeById(id);
        return ResultVO.success(res);
    }
}

